// Package entity Package avatarModel -----------------------------
// @file      : avatarModel.go
// @author    : WuZhouHai
// @contact   : wzh200x@126.com
// @time      : 2024/4/17 11:56
// @desc      :
// -------------------------------------------
package entity

import (
	"github.com/gogf/gf/v2/errors/gcode"
	"github.com/gogf/gf/v2/errors/gerror"
	"github.com/gogf/gf/v2/util/gmeta"
	"phoenix/phoenix/common/logger"
	"phoenix/phoenix/defines/dataType"
	error2 "phoenix/phoenix/defines/error"
	"phoenix/phoenix/entitys/entityModel"
	"phoenix/phoenix/interfaces"
	"phoenix/phoenix/managers/databaseManager"
	"phoenix/phoenix/utils"
)

type AvatarModelData struct {
	gmeta.Meta  `orm:"table: avatar"`
	AvatarId    dataType.PhoenixTypeDataBaseId `orm:"id"`          // 角色ID
	AccountName string                         `orm:"account"`     // 账号
	AvatarName  string                         `orm:"name"`        // 角色名称
	Job         int32                          `orm:"job"`         // 职业
	LoginTime   string                         `orm:"login_time"`  // 登录时间
	CreateTime  string                         `orm:"create_time"` // 创建时间
}

func (this *AvatarModelData) Reset() {
	this.AvatarId = 0
	this.AccountName = ""
	this.AvatarName = ""
	this.Job = 0
	this.LoginTime = ""
	this.CreateTime = ""
}

type AvatarModel struct {
	entityModel.EntityModel
}

func (this *AvatarModel) LoadEntityDataFromDB(records interface{}) error {
	base, err := databaseManager.PhoenixManagerDatabase().DefaultDataBase()
	if err != nil {
		return err
	}
	if entityData, ok := this.EntityData.(*AvatarModelData); ok {
		one, err := base.GetDb().Model(this.Template).Where("account", entityData.AccountName).One()
		if err != nil {
			return err
		}
		if one == nil {
			return this.Create()
		}
		err = one.Struct(this.EntityData)
		this.SetEntityDBID(entityData.AvatarId)
		return nil
	}
	return gerror.NewCodef(gcode.New(error2.PHOENIX_ERROR_ENTITY_PROPERTY_INVALID, "", nil),
		"avatar module model data is invalid")
}

func (this *AvatarModel) Create() error {
	if entityData, ok := this.EntityData.(*AvatarModelData); ok {
		entityData.CreateTime = utils.GetNowTimeFormat()
		entityData.LoginTime = utils.GetNowTimeFormat()
		err := this.CreateDataToDB()
		entityData.AvatarId = this.EntityDBID
		if err != nil {
			return err
		}
		logger.PhoenixLoggerIns().Debug("create avatar base success")
		return nil
	}
	return gerror.NewCodef(gcode.New(error2.PHOENIX_ERROR_ENTITY_PROPERTY_INVALID, "", nil),
		"avatar module model create fail, data is invalid")
}

func NewAvatarModel(name string) interfaces.IEntityModel {
	m := &AvatarModel{
		EntityModel: entityModel.NewEntityModel(name),
	}
	m.SetEntityData(&AvatarModelData{
		AvatarId:    0,
		AccountName: "",
		AvatarName:  "",
		Job:         0,
		LoginTime:   "",
		CreateTime:  "",
	})
	m.SetTemplate(m.EntityData)
	return m
}
